package com.etrans.web.gps.business.system.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.system.domain.EntCheck;
import com.etrans.web.gps.business.system.domain.EntCheckCmd;
import com.etrans.web.gps.business.system.domain.QueryEntCheck;
import com.etrans.web.gps.business.system.domain.Strategy;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.MongodbConfig;
import com.mongodb.BasicDBObject;

/**
 * 业户查岗service
 * 
 * @author Tan
 *
 */
@Service
public class EntCheckService extends BaseService {

	private static final Logger logger = LoggerFactory.getLogger(EntCheckService.class);
	
	@Autowired
	private MGTemplete mgTemplete; // mongodb 操作类

	
	/**
	 * 业户查岗列表
	 * 
	 * @return List<EntCheck>
	 */

	@SuppressWarnings({ "static-access", "unchecked" })
	public List<QueryEntCheck> queryEntCheckList(Map<String, Object> paramMap) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 查询条件封装
		BasicDBObject query = new BasicDBObject();
		HashMap<String, Object> lookUpMap = new HashMap<String, Object>();
		HashMap<String, Date> where = new HashMap<>();
		HashMap<String, List<Integer>> where_unitIds = new HashMap<>();	// 数据权限过滤
		HashMap<String, Object> sortMap = new HashMap<String, Object>();
		HashMap<String, Object> projectMap = new HashMap<String, Object>();
		HashMap<String, Object> unwindMap = new HashMap<String, Object>();
		

		// 开始时间
		String start_Time = paramMap.get("startTime")== null ? "": paramMap.get("startTime").toString();	
		// 结束时间
		String end_Time = paramMap.get("endTime")== null ? "":paramMap.get("endTime").toString();
				
		if (StringUtils.isNotBlank(start_Time) && StringUtils.isNotBlank(end_Time)) {
			try {
				where.put("$gte", format.parse(start_Time+" 00:00:00"));// 大于
				where.put("$lte", format.parse(end_Time+" 23:59:59"));// 小于
				query.put("check_time",where);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		// 业户查岗id
		String checkUnitId = paramMap.get("checkUnitId")== null ? "" : paramMap.get("checkUnitId").toString();
		if(StringUtils.isNotBlank(checkUnitId)){
			List<Integer> listUnitIds = new ArrayList<>();
			String[] ids = checkUnitId.split(",");
			for (String id : ids) {
				listUnitIds.add(Integer.valueOf(id));
			}
			where_unitIds.put("$in", listUnitIds);
			query.put("check_unit_id", where_unitIds);
		}else{
			if(paramMap.get("listCheckUnitIds")!=null){
				List<HashMap<String, Object>> listCheckUnitIds = (List<HashMap<String, Object>>) paramMap.get("listCheckUnitIds");
				List<Integer> listUnitIds = new ArrayList<>();
				if(listCheckUnitIds != null && listCheckUnitIds.size() > 0 ){
					for (HashMap<String, Object> hashMap : listCheckUnitIds) {
						listUnitIds.add(Integer.valueOf(hashMap.get("id").toString()));
					}
					where_unitIds.put("$in", listUnitIds);
					query.put("check_unit_id", where_unitIds);
				}else{
					logger.info("当前登录人查询业户查岗记录操作---->数据权限---->当前登录人没有区域对应的业户id step1");
				}
			}else{
				logger.info("当前登录人查询业户查岗记录操作---->数据权限---->当前登录人没有区域对应的业户id step2");
			}
		}

		int page 	  = Integer.valueOf(paramMap.get("page").toString());		// 当前显示页数
		int pageSize  = Integer.valueOf(paramMap.get("pageSize").toString());	// 每页记录数
		
		// 排序
		String sortorder = paramMap.get("sortorder").toString();
		if(StringUtils.isNotBlank(sortorder)){
			if(sortorder.contains("desc")){
				sortMap.put("check_time", Constant.MONGODB_DESC);					// 降序排序
			}
			if(sortorder.contains("asc")){
				sortMap.put("check_time", Constant.MONGODB_ASC);					// 升序排序
			}
		}
		
		List<QueryEntCheck> resultList = new ArrayList<QueryEntCheck>();
		// 构造lookUp查询条件
		lookUpMap.put("from", MongodbConfig.MONGODB_TABLE_POST_CHECK);
		lookUpMap.put("localField", "check_id");
		lookUpMap.put("foreignField", "_id");
		lookUpMap.put("as", "entCheck");
		unwindMap.put("unwind", "$entCheck");
		projectMap.put("_id", 				"$entCheck._id");			// post_check 表所有字段
		projectMap.put("checker", 			"$entCheck.checker");		// post_check 表所有字段
		projectMap.put("check_time", 		"$entCheck.check_time");	// post_check 表所有字段
		projectMap.put("check_content", 	"$entCheck.check_content");	// post_check 表所有字段
		projectMap.put("answer", 			"$entCheck.answer");		// post_check 表所有字段
		projectMap.put("check_type", 		"$entCheck.check_type");	// post_check 表所有字段
		projectMap.put("check_id", 			1);		// post_check_cmd uuid
		projectMap.put("check_unit_id", 	1);		// post_check_cmd 查岗业户ID
		projectMap.put("check_unit_name",   1);		// post_check_cmd 查岗业户名称
		projectMap.put("reply_time", 		1);		// post_check_cmd 回复时间
		projectMap.put("reply_content", 	1);		// post_check_cmd 回复内容
		projectMap.put("check_result", 		1);		// post_check_cmd 查岗结果 1:正确 2:错误 3:超时 4:未应答 
		// 查询符合时间条件的所有车辆
		resultList = mgTemplete.aggregateTable(MongodbConfig.MONGODB_DB, MongodbConfig.MONGODB_TABLE_POST_CHECK_CMD, query,unwindMap, lookUpMap, sortMap,projectMap,page,pageSize, QueryEntCheck.class);

		return resultList;
	}

	/**
	 * 业户查岗总条数
	 * 
	 * @return List<EntCheck>
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	public Integer queryEntCheckListCount(Map<String, Object> paramMap) {
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	

		// 查询条件封装
		BasicDBObject query = new BasicDBObject();
		HashMap<String, Object> lookUpMap = new HashMap<String, Object>();
		HashMap<String, Date> where = new HashMap<>();
		HashMap<String, List<Integer>> where_unitIds = new HashMap<>();	// 数据权限过滤
		HashMap<String, Object> sortMap = new HashMap<String, Object>();
		HashMap<String, Object> projectMap = new HashMap<String, Object>();
		HashMap<String, Object> unwindMap = new HashMap<String, Object>();
		

		// 开始时间
		String start_Time = paramMap.get("startTime")== null ? "": paramMap.get("startTime").toString();	
		// 结束时间
		String end_Time = paramMap.get("endTime")== null ? "":paramMap.get("endTime").toString();
				
		if (StringUtils.isNotBlank(start_Time) && StringUtils.isNotBlank(end_Time)) {
			try {
				where.put("$gte", format.parse(start_Time+" 00:00:00"));// 大于
				where.put("$lte", format.parse(end_Time+" 23:59:59"));// 小于
				query.put("check_time",where);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		// 业户查岗id
		String checkUnitId = paramMap.get("checkUnitId")== null ? "" : paramMap.get("checkUnitId").toString();
		if(StringUtils.isNotBlank(checkUnitId)){
			List<Integer> listUnitIds = new ArrayList<>();
			String[] ids = checkUnitId.split(",");
			for (String id : ids) {
				listUnitIds.add(Integer.valueOf(id));
			}
			where_unitIds.put("$in", listUnitIds);
			query.put("check_unit_id", where_unitIds);
		}else{
			if(paramMap.get("listCheckUnitIds")!=null){
				List<HashMap<String, Object>> listCheckUnitIds = (List<HashMap<String, Object>>) paramMap.get("listCheckUnitIds");
				List<Integer> listUnitIds = new ArrayList<>();
				if(listCheckUnitIds != null && listCheckUnitIds.size() > 0 ){
					for (HashMap<String, Object> hashMap : listCheckUnitIds) {
						listUnitIds.add(Integer.valueOf(hashMap.get("id").toString()));
					}
					where_unitIds.put("$in", listUnitIds);
					query.put("check_unit_id", where_unitIds);
				}else{
					logger.info("当前登录人查询业户查岗记录操作---->数据权限---->当前登录人没有区域对应的业户id step1");
				}
			}else{
				logger.info("当前登录人查询业户查岗记录操作---->数据权限---->当前登录人没有区域对应的业户id step2");
			}
		}

		
		// 排序
		String sortorder = paramMap.get("sortorder").toString();
		if(StringUtils.isNotBlank(sortorder)){
			if(sortorder.contains("desc")){
				sortMap.put("check_time", Constant.MONGODB_DESC);					// 降序排序
			}
			if(sortorder.contains("asc")){
				sortMap.put("check_time", Constant.MONGODB_ASC);					// 升序排序
			}
		}
		
		// 构造lookUp查询条件
		lookUpMap.put("from", MongodbConfig.MONGODB_TABLE_POST_CHECK);
		lookUpMap.put("localField", "check_id");
		lookUpMap.put("foreignField", "_id");
		lookUpMap.put("as", "entCheck");
		unwindMap.put("unwind", "$entCheck");
		projectMap.put("_id", 				"$entCheck._id");			// post_check 表所有字段
		projectMap.put("checker", 			"$entCheck.checker");		// post_check 表所有字段
		projectMap.put("check_time", 		"$entCheck.check_time");	// post_check 表所有字段
		projectMap.put("check_content", 	"$entCheck.check_content");	// post_check 表所有字段
		projectMap.put("answer", 			"$entCheck.answer");		// post_check 表所有字段
		projectMap.put("check_type", 		"$entCheck.check_type");	// post_check 表所有字段
		projectMap.put("check_id", 			1);		// post_check_cmd uuid
		projectMap.put("check_unit_id", 	1);		// post_check_cmd 查岗业户ID
		projectMap.put("check_unit_name",   1);		// post_check_cmd 查岗业户名称
		projectMap.put("reply_time", 		1);		// post_check_cmd 回复时间
		projectMap.put("reply_content", 	1);		// post_check_cmd 回复内容
		projectMap.put("check_result", 		1);		// post_check_cmd 查岗结果 1:正确 2:错误 3:超时 4:未应答 
		// 查询符合时间条件的所有车辆
		Integer count = mgTemplete.aggregateTableCount(MongodbConfig.MONGODB_DB, MongodbConfig.MONGODB_TABLE_POST_CHECK_CMD, query,unwindMap, lookUpMap, sortMap,projectMap, QueryEntCheck.class);
		return count;
	}

	/**
	 * 业户查岗策略设置列表查询
	 * 
	 * @return List<Strategy>
	 */
	public List<Strategy> queryEntAllStrategys(Map<String, Object> params) {
		return this.selectList("strategyQuery.queryEntAllStrategys", params);
	}

	
	/**
	 * 业户查岗策略设置总条数
	 * 
	 * @return long
	 */
	public long entAllStrategysCount(Map<String, Object> params) {
		return (Long) this.selectOne("strategyQuery.entAllStrategysCount", params);
	}
	

	/**
	 * 查岗策略设置删除
	 * 
	 * @return int
	 */
	public int deleteStrategy(int strategyId) {
		return this.delete("strategyMapper.deleteStrategy", strategyId);
		
	}

	/**
	 * 查岗策略设置保存
	 * 
	 * @return int
	 */
	public int saveStrategy(Strategy strategy) {
		this.insert("strategyMapper.saveStrategy", strategy);
		return strategy.getId();
	}

	/**
	 * 查岗方式：手动 业户查岗保存MONGODB
	 * @param areaCheck
	 */
	@SuppressWarnings("static-access")
	public void insertEntCheckToMongodb(EntCheck entCheck) {
		mgTemplete.insertOne(MongodbConfig.MONGODB_DB, MongodbConfig.MONGODB_TABLE_POST_CHECK, entCheck);
	}

	/**
	 * 查岗方式：手动 业户查岗保存MONGODB
	 * @param areaCheck
	 */
	@SuppressWarnings("static-access")
	public void insertEntCheckCmdToMongodb(EntCheckCmd entCheckCmd) {
		mgTemplete.insertOne(MongodbConfig.MONGODB_DB, MongodbConfig.MONGODB_TABLE_POST_CHECK_CMD, entCheckCmd);
	}

	

	

	
}
